import 'dart:io';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:giwiki/entities/entities.dart';
import 'package:giwiki/entities/entities_data.dart';

import '../components/info_dialog.dart';

class WeaponDetailScreen extends StatefulWidget {
  final Weapon c;

  const WeaponDetailScreen(this.c, {super.key});

  @override
  State<StatefulWidget> createState() => _WeaponDetailScreenState();
}

class _WeaponDetailScreenState extends State<WeaponDetailScreen> {
  final ScrollController _scrollController = ScrollController();

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    var sw = min(size.width, size.height);
    var sh = max(size.width, size.height);
    var imageSize = sw - 40;
    return Scaffold(
      extendBodyBehindAppBar: true,
      body: Stack(
        children: [
          ListView(
            controller: _scrollController,
            padding: EdgeInsets.zero,
            children: [
              SafeArea(
                bottom: false,
                child: Container(),
              ),
              Stack(children: [
                _cCard(imageSize, size.width < size.height),
                Align(
                  alignment: Alignment.topRight,
                  child: Padding(
                    padding: const EdgeInsets.only(right: 10, top: 12),
                    child: _moreMatInfoIcon(imageSize),
                  ),
                ),
              ]),
              Container(height: 10),
              _ver(),
              Container(height: 10),
              _story(),
              SafeArea(
                top: false,
                child: Container(),
              ),
            ],
          ),
          _buildReturn(),
        ],
      ),
    );
  }

  Widget _buildReturn() {
    return SafeArea(
      child: Align(
        alignment: Alignment.topLeft,
        child: IconButton(
          icon: const Icon(
            Icons.arrow_back,
            color: Colors.white,
            shadows: [
              Shadow(
                color: Colors.black,
                offset: Offset(1, 1),
                blurRadius: 1,
              ),
            ],
          ),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
    );
  }

  Widget _cCard(double imageSize, bool isPortrait) {
    return Card(
      color: const Color(0xff27363e),
      clipBehavior: Clip.hardEdge,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.all(Radius.circular(8.0)),
      ),
      child: Column(
        children: [
          Container(height: 25),
          Text(
            widget.c.name,
            style: const TextStyle(
              color: Colors.white,
              fontSize: 24,
              fontWeight: FontWeight.bold,
            ),
          ),
          Container(height: 12),
          Text(
            "★" * widget.c.rank,
            style: const TextStyle(
              color: Colors.white,
              fontSize: 14,
              fontWeight: FontWeight.bold,
            ),
          ),
          Container(height: 8),
          Container(height: 32),
          LayoutBuilder(
            builder: (BuildContext context, BoxConstraints constraints) {
              return SizedBox(
                width: constraints.maxWidth,
                child: Wrap(
                  alignment: WrapAlignment.spaceEvenly,
                  children: [
                    for (var icon in widget.c.icons)
                      Container(
                        decoration: BoxDecoration(
                          border: Border.all(
                            color: Colors.white.withOpacity(.3),
                            width: .5,
                          ),
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Image.file(
                          File("$repo/pics/Weapon/$icon.png"),
                          width: imageSize / 2,
                        ),
                      ),
                  ],
                ),
              );
            },
          ),
          const Text(
            "",
            style: TextStyle(
              color: Colors.white,
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          Text(
            "${intCalc(widget.c.stat)} 攻击力 / ${weaponCustom(widget.c.custom, widget.c.customstat)}",
            style: const TextStyle(
              color: Colors.white,
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const Text(
            "",
            style: TextStyle(
              color: Colors.white,
              fontSize: 12,
              fontWeight: FontWeight.bold,
            ),
          ),
          Text(
            " ( ${_matText(widget.c.ascmatid)} )",
            style: TextStyle(
              color: Colors.white.withOpacity(.7),
              fontWeight: FontWeight.bold,
            ),
          ),
          Container(height: 12),
          Text.rich(
            textAlign: TextAlign.center,
            TextSpan(
              children: [
                _buildItemMatIcon(widget.c.ascmatid, imageSize),
                for (var mat in widget.c.matids) ...[
                  WidgetSpan(child: Container(width: 18)),
                  _buildItemMatIcon(mat, imageSize),
                ],
              ],
            ),
          ),
          const Text(
            "",
            style: TextStyle(
              color: Colors.white,
              fontSize: 12,
              fontWeight: FontWeight.bold,
            ),
          ),
          _desc(),
          const Text(
            "",
            style: TextStyle(
              color: Colors.white,
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
        ],
      ),
    );
  }

  Widget _moreMatInfoIcon(double imageSize) {
    return GestureDetector(
      onTap: () {
        showMatCountDialog(context, widget.c, imageSize);
      },
      child: const Icon(
        Icons.unfold_more_outlined,
        color: Colors.white,
        size: 28,
      ),
    );
  }

  void showMatCountDialog(BuildContext context, Weapon c, double imageSize) {
    infoDialog(
      context,
      canPop: true,
      backgroundColor: const Color(0xff27363e),
      title:
          Text("${c.name} - 材料", style: const TextStyle(color: Colors.white)),
      content: Column(children: [
        Container(height: 10),
        Table(
            defaultVerticalAlignment: TableCellVerticalAlignment.middle,
            children: [
              TableRow(children: [
                Text.rich(
                  TextSpan(
                      children: [_buildItemMatIcon(c.ascmatid, imageSize)]),
                ),
                Text(
                    c.rank == 5
                        ? "6"
                        : c.rank == 4
                            ? "4"
                            : "3",
                    style: const TextStyle(color: Colors.white)),
                if (itemsMap.containsKey(c.ascmatid - 1)) ...[
                  Text.rich(
                    TextSpan(children: [
                      _buildItemMatIcon(c.ascmatid - 1, imageSize)
                    ]),
                  ),
                  Text(
                      c.rank == 5
                          ? "14"
                          : c.rank == 4
                              ? "9"
                              : "6",
                      style: const TextStyle(color: Colors.white)),
                ],
                if (itemsMap.containsKey(c.ascmatid - 2)) ...[
                  Text.rich(
                    TextSpan(children: [
                      _buildItemMatIcon(c.ascmatid - 2, imageSize)
                    ]),
                  ),
                  Text(
                      c.rank == 5
                          ? "14"
                          : c.rank == 4
                              ? "9"
                              : "6",
                      style: const TextStyle(color: Colors.white)),
                ],
                if (itemsMap.containsKey(c.ascmatid - 3)) ...[
                  Text.rich(
                    TextSpan(children: [
                      _buildItemMatIcon(c.ascmatid - 3, imageSize)
                    ]),
                  ),
                  Text(
                      c.rank == 5
                          ? "5"
                          : c.rank == 4
                              ? "3"
                              : "2",
                      style: const TextStyle(color: Colors.white)),
                ],
              ]),
              for (var i = 0; i < widget.c.matids.length; i++) ...[
                if (i == 0) ...[
                  TableRow(children: [
                    Text.rich(
                      TextSpan(children: [
                        _buildItemMatIcon(widget.c.matids[i], imageSize)
                      ]),
                    ),
                    Text(
                        c.rank == 5
                            ? "41"
                            : c.rank == 4
                                ? "27"
                                : "18",
                        style: TextStyle(color: Colors.white)),
                    if (itemsMap.containsKey(widget.c.matids[i] - 1)) ...[
                      Text.rich(
                        TextSpan(children: [
                          _buildItemMatIcon(widget.c.matids[i] - 1, imageSize)
                        ]),
                      ),
                      Text(
                          c.rank == 5
                              ? "27"
                              : c.rank == 4
                                  ? "18"
                                  : "12",
                          style: TextStyle(color: Colors.white)),
                    ],
                    if (itemsMap.containsKey(widget.c.matids[i] - 2)) ...[
                      Text.rich(
                        TextSpan(children: [
                          _buildItemMatIcon(widget.c.matids[i] - 2, imageSize)
                        ]),
                      ),
                      Text(
                          c.rank == 5
                              ? "23"
                              : c.rank == 4
                                  ? "15"
                                  : "10",
                          style: TextStyle(color: Colors.white)),
                    ],
                    Text(""),
                    Text(""),
                  ]),
                ],
                if (i == 1) ...[
                  TableRow(children: [
                    Text.rich(
                      TextSpan(children: [
                        _buildItemMatIcon(widget.c.matids[i], imageSize)
                      ]),
                    ),
                    Text(
                        c.rank == 5
                            ? "27"
                            : c.rank == 4
                                ? "18"
                                : "12",
                        style: TextStyle(color: Colors.white)),
                    if (itemsMap.containsKey(widget.c.matids[i] - 1)) ...[
                      Text.rich(
                        TextSpan(children: [
                          _buildItemMatIcon(widget.c.matids[i] - 1, imageSize)
                        ]),
                      ),
                      Text(
                          c.rank == 5
                              ? "23"
                              : c.rank == 4
                                  ? "15"
                                  : "10",
                          style: TextStyle(color: Colors.white)),
                    ],
                    if (itemsMap.containsKey(widget.c.matids[i] - 2)) ...[
                      Text.rich(
                        TextSpan(children: [
                          _buildItemMatIcon(widget.c.matids[i] - 2, imageSize)
                        ]),
                      ),
                      Text(
                          c.rank == 5
                              ? "15"
                              : c.rank == 4
                                  ? "10"
                                  : "6",
                          style: TextStyle(color: Colors.white)),
                    ],
                    Text(""),
                    Text(""),
                  ]),
                ],
              ],
            ]),
        Container(height: 10),
      ]),
    );
  }

  InlineSpan _buildText(String text) {
    return TextSpan(
      text: text,
      style: const TextStyle(
        color: Colors.white,
        fontSize: 18,
        fontWeight: FontWeight.bold,
      ),
    );
  }

  InlineSpan _buildElementIcon(String element) {
    return WidgetSpan(
      alignment: PlaceholderAlignment.middle,
      child: Image.file(
        File("$repo/pics/Csxylic/$element.png"),
        width: 36,
      ),
    );
  }

  InlineSpan _buildItemMatIcon(int weekmat, double imageSize) {
    var item = itemsMap[weekmat];
    if (item == null) {
      return const TextSpan();
    }
    var itemIcon = item.icon;
    return WidgetSpan(
      alignment: PlaceholderAlignment.middle,
      child: GestureDetector(
        onTap: () async {
          await infoDialog(
            context,
            canPop: true,
            backgroundColor: const Color(0xff27363e),
            title: Text.rich(TextSpan(children: [
              WidgetSpan(
                alignment: PlaceholderAlignment.middle,
                child: Image.file(
                  File("$repo/pics/Item/$itemIcon.png"),
                  width: 36,
                ),
              ),
              TextSpan(
                text: item.name,
                style: const TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ])),
            content: SizedBox(
              width: imageSize,
              child: Column(
                children: [
                  if (item.desc.isNotEmpty)
                    Html(
                      data: item.src.join("<br>"),
                      style: {
                        "html": Style(
                          color: Colors.white.withAlpha(200),
                          fontSize: FontSize(12),
                        ),
                      },
                    ),
                  if (item.desc.isNotEmpty) Container(height: 10),
                  Html(
                    data: item.desc,
                    style: {
                      "html": Style(
                        color: Colors.white,
                        fontSize: FontSize(16),
                      ),
                    },
                  ),
                ],
              ),
            ),
          );
        },
        child: Image.file(
          File("$repo/pics/Item/$itemIcon.png"),
          width: 36,
        ),
      ),
    );
  }

  Widget _desc() {
    return Container(
      padding: const EdgeInsets.only(
        left: 10,
        right: 10,
      ),
      child: Text(
        widget.c.desc,
        style: const TextStyle(
          color: Colors.white,
        ),
      ),
    );
  }

  Widget _ver() {
    var wa = weaponAffixesMap[widget.c.equipaffixid];
    if (wa == null) {
      return Container();
    }
    List lastVer = [...wa.ver.keys];
    lastVer.sort((a, b) => -a.compareTo(b));
    var key = lastVer.first;
    var ver = wa.ver[key]!;
    ver.join("\n");
    return Card(
      color: const Color(0xff27363e),
      clipBehavior: Clip.hardEdge,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.all(Radius.circular(8.0)),
      ),
      child: Container(
        padding: const EdgeInsets.only(
          left: 10,
          right: 10,
        ),
        child: Html(
          data: ver
              .join("\n")
              .replaceAll("<color", "<font")
              .replaceAll("/color>", "/font>")
              .replaceAll("#99FFFFFF", "#FFFFB44B"),
          style: {
            "html": Style(
              color: Colors.white,
              fontSize: FontSize(16),
            ),
          },
        ),
      ),
    );
  }

  Widget _story() {
    var story = weaponStoriesMap[widget.c.story];
    if (story == null) {
      return const Text("");
    }
    return Card(
      color: const Color(0xff27363e),
      clipBehavior: Clip.hardEdge,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.all(Radius.circular(8.0)),
      ),
      child: Html(
        data: story.story
            .join("\n")
            .replaceAll("<color", "<font")
            .replaceAll("/color>", "/font>"),
        style: {
          "html": Style(
            color: Colors.white,
            fontSize: FontSize(16),
          ),
        },
      ),
    );
  }
}

Color elementColor(String element, Color defaultColor) {
  switch (element) {
    case "Water":
      return const Color(0xff81bffd);
    case "Elec":
      return const Color(0xffffaafc);
    case "Grass":
      return const Color(0xff96fd8f);
    case "Fire":
      return const Color(0xffff9999);
    case "Rock":
      return const Color(0xfffde69d);
    case "Wind":
      return const Color(0xff78f2cf);
    case "Ice":
      return const Color(0xff98ffff);
    default:
      return defaultColor;
  }
}

const _skillInnerPadding = EdgeInsets.only(
  left: 10,
  right: 10,
  top: 3,
  bottom: 8,
);

String weaponCustom(String custom, double customstat) {
  var response = "";
  if (custom == "EM") {
    response += intCalc(customstat);
  } else {
    response += percentageCalc(customstat);
  }
  response += " ";
  switch (custom) {
    case "ATK":
      response += "攻击力";
      break;
    case "HP":
      response += "生命值";
      break;
    case "DEF":
      response += "防御力";
      break;
    case "CR":
      response += "暴击率";
      break;
    case "CD":
      response += "暴击伤害";
      break;
    case "ER":
      response += "元素充能效率";
      break;
    case "EM":
      response += "元素精通";
      break;
    case "Phys":
      response += "物理伤害加成";
      break;
  }
  return response;
}

String intCalc(double value) {
  return value.toStringAsFixed(0);
}

String percentageCalc(double value) {
  return "${(value * 100).toStringAsFixed(1)}%";
}

String _matText(int talentmat) {
  var t = weaponAscensionsMap[talentmat];
  if (t == null) {
    return "";
  }
  switch (t.period) {
    case 1:
      return "一 / 四 / 日";
    case 2:
      return "二 / 五 / 日";
    case 3:
      return "三 / 六 / 日";
    default:
      return "";
  }
}
